package main

import (
	"net"
	"fmt"
	"os"
	"io"
)

//接收文件操作
func RecvFile(path string,conn net.Conn){
	//新建文件
	f,err := os.Create(path)
	if err != nil{
		fmt.Println("err=",err)
		return
	}

	buff := make([]byte,1024)
	for{
		n,err := conn.Read(buff)
		if err != nil{
			if err == io.EOF{
				fmt.Println("文件接收完毕")
			}else{
				fmt.Println("err=",err)
			}
			return
		}

		if n == 0{
			fmt.Println("n==0 文件接收完毕")
			break
		}

		f.Write(buff[:n])
	}

}

func main(){
	//创建监听
	listener,err := net.Listen("tcp","127.0.0.1:8000")
	if err != nil{
		fmt.Println("err=",err)
		return
	}

	defer listener.Close()

	//等待用户连接
	conn ,err := listener.Accept()
	if err != nil{
		fmt.Println("err=",err)
		return
	}

	defer conn.Close()

	//创建接收数据buff
	buff := make([]byte,1024)

	n,err := conn.Read(buff)
	if err != nil{
		fmt.Println("err=",err)
		return
	}

	fileName := string(buff[:n])

	//回复 ok
	conn.Write([]byte("ok"))

	//接收文件内容
	RecvFile(fileName ,conn)

}
